package com.dc.chat.interceptor.security;

import com.dc.chat.entity.to.ResponseBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class BackInterceptor implements HandlerInterceptor {
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            if(request.getMethod().equals("OPTIONS")){
                return true;
            }
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            Admin methodAnnotation = handlerMethod.getMethodAnnotation(Admin.class);
            if(methodAnnotation!=null){
                String token = request.getHeader("token");
                String admin = (String) redisTemplate.opsForValue().get(token);
                if(admin!=null&&admin.equals("admin")){
                    return true;
                }else{
                    throw new RuntimeException("没有携带管理员token信息");
                }
            }else{
                return true;
            }
        }catch (Exception e){
            response.setContentType("application/json; charset = utf-8");
            PrintWriter writer = response.getWriter();
            ResponseBean responseBean=new ResponseBean();
            responseBean.setCode(401);
            responseBean.setMessage("请登录后在访问该内容");
            ObjectMapper objectMapper=new ObjectMapper();
            String json = objectMapper.writeValueAsString(responseBean);
            writer.write(json);
            writer.close();
            return  false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
